#!/usr/bin/python

# To change this template, choose Tools | Templates
# and open the template in the editor.

__author__="gabor"
__date__ ="$2010.10.14. 21:16:43$"

import dbus, dbus.glib
import gobject
import time
import calendar
import datetime
import math

## Time between RM Calls: ensures that bus is not overloaded
sleep_time=2

## Timestamp of the most recently saved data
device_logged_tms={}

## Functions

def log_to_file(EUI,name,live_data_float):
    if (len(live_data_float)==18):
        # opening file
        t=time.time()
        t2=time.localtime()
        filename='logs/%s_%s'%(name,EUI)
        #Checking if file exists
        try:
            f_log_handle=open(filename,'r')
            exists=1
            #print('%s file exists.'%filename)
            f_log_handle.close()
        except IOError:
            exists=0
            #print('%s file does not exist.'%filename)

        # Converting device timestamp to Unix format
        # converting to int
        try:
            year_int=int(live_data_float['year'])
            month_int=int(live_data_float['month'])
            day_int=int(live_data_float['day'])
            hour_int=int(live_data_float['hour'])
            min_int=int(live_data_float['min'])
            sec_int=int(live_data_float['sec'])
            
            weekday=calendar.weekday(year_int,month_int,day_int)
            yearday=datetime.date(year_int,month_int,day_int).toordinal()-datetime.date(year_int,1,1).toordinal()+1
            devicetime=time.mktime((year_int,month_int,day_int,hour_int,min_int,sec_int,weekday,yearday,-1))
            
        except ValueError:
            devicetime=float('nan')



        
        # Checking if value has been logged already
        if(device_logged_tms.has_key(EUI)):
#            if (device_logged_tms[EUI]<devicetime)|(devicetime==float('nan')):
#                pass
#            else:
#                print 'Values from %s has been logged already.'%(name)
#                return 1
            if ((device_logged_tms[EUI]==devicetime) | (math.isnan(device_logged_tms[EUI]) & math.isnan(devicetime))):
                print 'Values from %s has been logged already.'%(name)
                return 1
            else:
                pass

        # Writing to file
        try:
            f_log_handle=open(filename,'a')
            # Printing header if file does not exist
            if (exists==0):
                f_log_handle.write('#PC Time at file writing\tDevice Time\tPlogg Uptime\tEqu. on time\tWatts\tkWh(G)\tkWh(C)\tFreq\tRMS V\tRMS C\tReac.P.\tVARh(G)\tVARh(C)\tPhase angle\r\n')
            #writing PC time
            #f_log_handle.write('%4d.%2.2d.%2.2d_%2.2d:%2.2d.%2.2d\t'%(t[0],t[1],t[2],t[3],t[4],t[5]))
            f_log_handle.write('%f\t'%(t))

            #writing live info
            
            
            f_log_handle.write('%.0f\t'%(devicetime))
            # Plogg uptime
            f_log_handle.write("%f\t"%(live_data_float['ontime']))
            #Equipment on time

            f_log_handle.write("%f\t"%(live_data_float['eq_ontime']))

            # Other values
            f_log_handle.write("%-.3f\t"%live_data_float['watts'])
            f_log_handle.write("%-.4f\t"%live_data_float['cg_watts'])
            f_log_handle.write("%-.4f\t"%live_data_float['cc_watts'])

            f_log_handle.write("%-.1f\t"%live_data_float['freq'])
            f_log_handle.write("%-.3f\t"%live_data_float['voltage'])
            f_log_handle.write("%-.3f\t"%live_data_float['current'])

            f_log_handle.write("%-.3f\t"%live_data_float['vars'])
            f_log_handle.write("%-.4f\t"%live_data_float['cg_vars'])
            f_log_handle.write("%-.4f\t"%live_data_float['cc_vars'])
            f_log_handle.write("%.0f\r\n"%live_data_float['phase'])

            f_log_handle.close()

            #printing logged values
            print('Data logged from %s at %2.2d.%2.2d %2.2d:%2.2d.%2.2d: %-.3fW %-.3fvar'%(name,t2[1],t2[2],t2[3],t2[4],t2[5],live_data_float['watts'],live_data_float['vars']))
            # updating device_logged_tms
            device_logged_tms[EUI]=devicetime
            return 1


        except IOError:
            print('excetion at file opening')
            return 0




def log_loop(Pm_service):
    # loop for fetching
    while 1:
        #time.sleep(1)
        try:
            devices=Pm_service.get_device_EUIs(1)
        except dbus.exceptions.DBusException,err:
            print str(err)
            print 'Manager service isn\'t running.'
            return
        time.sleep(sleep_time)
        for k,v in devices.iteritems():
            #Getting live_data from the manager service
            
            try:
                live_data_float=Pm_service.get_live_data(k)
                #print 'DEBUG ',live_data_float
            except dbus.exceptions.DBusException,err:
                print str(err)
                print 'Manager service isn\'t running.'
                return
            #print live_data
            log_to_file(k,v,live_data_float)
            time.sleep(sleep_time)
            

def main():
    print 'MIT_PM_LOGGER\n\n'
    print 'This application connects to the mit_pm_manager script through'
    print 'a dbus interface, named \'ca.amk.pm_service\','
    print 'and saves all measured value to file into /logs/ directory.\n\n'

    bus = dbus.SessionBus()
    while 1:
        try:
            Pm_service = dbus.Interface(bus.get_object('ca.amk.pm_service', '/'),'ca.amk.Interface')
            #Pm_service_2 = dbus.Interface(bus.get_object('ca.amk.pm_service', '/'),'ca.amk.Interface_2')
        except dbus.exceptions.DBusException,err:
            print str(err)
            print 'Manager service isn\'t running. Waiting...'
            time.sleep(sleep_time)

        ## We have link to the service
        log_loop(Pm_service)
        ## log_loop returns only when a dbus-exception is thrown


#    result=Pm_service.get_device_EUIs(1)
#    print result


#Main loop:
if __name__ == "__main__":
    main()
    


       



